package com.notary.tx_live_plugin.platform;

import android.content.Context;
import android.view.View;

import com.notary.tx_live_plugin.util.ChatManager;
import com.notary.tx_live_plugin.util.TxConstant;
import com.notary.tx_live_plugin.widget.TxLiveChatMeetView;

import java.util.HashMap;

import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.platform.PlatformView;

/**
 * 视频聊天会议 platformView
 */
public class ChatMeetPlatformView implements PlatformView {

    private final ChatManager chatManager;
    private MethodChannel channel;
    private TxLiveChatMeetView liveChatMeetView;
    private Context context;
    private final HashMap<String, Object> params;

    public ChatMeetPlatformView(BinaryMessenger binaryMessenger, Context context, int viewId, HashMap<String, Object> params) {
        this.context = context;
        this.params = params;
        //设置channel
        chatManager = ChatManager.getInstance();
        chatManager.setContext(context);
        ChatMethodCallHandlerImpl callHandler = new ChatMethodCallHandlerImpl(chatManager);
        final String channelName = TxConstant.Channel.CHAT_PREFIX + viewId;
        channel = new MethodChannel(binaryMessenger, channelName);
        channel.setMethodCallHandler(callHandler);
        chatManager.setOnChatCallback((String methodName, Object data) ->{
            if(channel != null)channel.invokeMethod(methodName,data);
        });
    }

    @Override
    public View getView() {
        if(liveChatMeetView == null) {
            liveChatMeetView =  new TxLiveChatMeetView(context);
            //liveChatMeetView.setParams(params);
            chatManager.setChatView(liveChatMeetView);
            chatManager.requestPermissionForPush();
        }
//        else{
//            pushManager.setPushView(liveChatMeetView);
//        }
        //else txLivePushView.onResume();
        return liveChatMeetView;
    }

    @Override
    public void dispose() {
        if(liveChatMeetView != null) liveChatMeetView.onDestroy();
        liveChatMeetView = null;
        chatManager.clear();
        context = null;
//        channel.setMethodCallHandler(null);
//        channel = null;
    }
}
